package com.sise.bl.service.impl;

import com.sise.bl.dao.UserDao;
import com.sise.bl.entity.User;
import com.sise.bl.service.UserService;
import com.sise.bl.utils.Constants;
import com.sise.bl.utils.EmailUtils;
import com.sise.bl.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional
@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    @Qualifier("userDao")
    private UserDao userDao;

    @Override
    public boolean checkedUser(String username) {
        User user = userDao.selectUserByUname(username);

        //处理返回值
        //user == null  false
        //user != null  true

        if (user != null) {
            return true;
        }
        return false;
    }

    @Override
    public int registerUser(User user) {
        //1. 将用户密码加密，添加用户
//        user.setUpassword(MD5Utils.md5(user.getUpassword()));
        int row = userDao.insertUser(user);

        //2.发送一封邮件
        EmailUtils.sendEmail(user);

        return row;
    }

    @Override
    public int activeUser(String code) {

        //1.根据激活码查找用户
        User user = userDao.selectUserByCode(code);

        //2.判断用户是否激活
        if (user.getUstatus() == Constants.ACTIVE_SUCCESS) {
            return Constants.ACTIVE_ALREADY;
        }

        //3.进行激活操作
        user.setUstatus(1);
        int i = userDao.updateUser(user);

        if (i > 0) {
            return Constants.ACTIVE_SUCCESS;
        }

        return Constants.ACTIVE_FAIL;
    }

    @Override
    public User login(String username, String password) {
        //1.需要密码用md5处理
        String md5password = MD5Utils.md5(password);
        //2.根据用户名查找用户
        User user = userDao.selectUserByUname(username);

        if (user != null && user.getUpassword().equals(md5password)) {
            return user;
        }

        return null;
    }

    @Override
    public User findByUid(String uid) {
        return userDao.selectUserById(Integer.valueOf(uid));
    }

    @Override
    public int updateUser(User user) {
        int i = userDao.updateUser(user);
        return i;
    }

    @Override
    public List<User> queryAll() {
        return userDao.selectAll();
    }

    @Override
    public User queryByName(String name) {
        User user = userDao.selectUserByUname(name);
        return user;
    }
}
